angular.module('ProduceWork').controller('MOCompleteRptController', ['$scope', '$http', 'PublicService', 'ExtendEnumService', 'BaseModule', 'BaseEnum', 'BaseFunction', 'BarcodeEnum', '$location', '$modal', 'Authentication',
	function($scope, $http, PublicService, ExtendEnumService, BaseModule, BaseEnum, BaseFunction, BarcodeEnum, $location, $modal, Authentication) {
		$scope.RcvTypeEnum;
		ExtendEnumService.getExtendEnum('RcvBusinessType', function(extendEnum) {
			$scope.RcvTypeEnum = extendEnum;
		});

		BaseModule.initModule($scope, 'RcvRecord');
		BaseModule.initModule($scope, '_RcvRecord');

		$scope.Module._RcvRecord.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;
		$scope.Module._RcvRecord.PageSize = 15;

		$scope.Module.RcvRecord.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;
		$scope.Module.RcvRecord.PageSize = 15;
		$scope.Module.RcvRecord.Populate = [{
			path: 'BarcodeMaster',
			select: 'Barcode MOLotNumber ShipLotNumber DescSeg1 DescSeg2'
		}, {
			path: 'ItemMaster',
			select: 'Code Name Specification'
		}, {
			path: 'BusinessDocID',
			select: 'Code',
			model: 'MO'
		}, {
			path: 'RcvUser',
			select: 'Name Department',
			model: 'User',
			populate: {
				path: 'Department',
				select: 'Name',
				model: 'Department'
			}
		}, {
			path: 'WareHouse',
			select: 'Name'
		}, {
			path: 'RcvOperation',
			select: 'Name',
			model: 'Operation'
		}, {
			path: 'Container',
			select: 'Name'
		}];

		//日期
		var curday = calCurrentMonthTime(true, 0);
		//var lastweekstart = calCurrentMonthTime(true, 1) + ' 00:00:00';
		//var lastweekend = calCurrentMonthTime(false, 1) + ' 23:59:59';
		var weekArr = getMonDayAndSunDay();
		var curweekstart = weekArr[0] + ' 00:00:00';
		var curweekend = weekArr[1] + ' 23:59:59';
		var lastweekstart = getLastMonDayAndSunDay(weekArr[0]) + ' 00:00:00';
		var lastweekend = getLastMonDayAndSunDay(weekArr[1]) + ' 23:59:59';
		//var curweekstart = calCurrentMonthTime(true, 2) + ' 00:00:00';
		//var curweekend = calCurrentMonthTime(false, 2) + ' 23:59:59';
		var lastmonthstart = calCurrentMonthTime(true, 3) + ' 00:00:00';
		var lastmonthend = calCurrentMonthTime(false, 3) + ' 23:59:59';
		var curmonthstart = calCurrentMonthTime(true, 4) + ' 00:00:00';
		var curmonthend = calCurrentMonthTime(false, 4) + ' 23:59:59';

		var condition = {
			RcvBusinessType: 0,
			RcvDateTime: {
				"$gte": curweekstart,
				"$lte": curweekend
			}
		};

		$scope.Module.RcvRecord.Condition = condition;

		$scope.Module.RcvRecord.PageSize = 15;
		$scope.Module.RcvRecord.load(condition);

		$scope.ProductComplete = true;
		$scope.ConnectArea = false;
		$scope.All = false;
		$scope.Day = false;
		$scope.LastWeek = false;
		$scope.CurrentWeek = true;
		$scope.LastMonth = false;
		$scope.CurrentMonth = false;
		$scope.AllDay = false;


		//成品完工
		$scope.cbRcvRpt = function() {
			if ($scope.ProductComplete) {
				$scope.ConnectArea = false;
				$scope.All = false;
				$scope.$digest();
				if ($scope.Day) {
					query(0, 0);
				} else if ($scope.LastWeek) {
					query(0, 1);
				} else if ($scope.CurrentWeek) {
					query(0, 2);
				} else if ($scope.LastMonth) {
					query(0, 3);
				} else if ($scope.CurrentMonth) {
					query(0, 4);
				} else if ($scope.AllDay) {
					query(0, 5);
				};

			} else {
				$scope.ProductComplete = true;
				$scope.$digest();
			}
		};

		//交接区入库
		$scope.cbConnect = function() {
			if ($scope.ConnectArea) {
				$scope.ProductComplete = false;
				$scope.All = false;
				$scope.$digest();

				if ($scope.Day) {
					query(1, 0);
				} else if ($scope.LastWeek) {
					query(1, 1);
				} else if ($scope.CurrentWeek) {
					query(1, 2);
				} else if ($scope.LastMonth) {
					query(1, 3);
				} else if ($scope.CurrentMonth) {
					query(1, 4);
				} else if ($scope.AllDay) {
					query(1, 5);
				};
			} else {
				$scope.ConnectArea = true;
				$scope.$digest();
			}
		};

		//全部类型
		$scope.cbRcvAll = function() {
			if ($scope.All) {
				$scope.ProductComplete = false;
				$scope.ConnectArea = false;
				$scope.$digest();

				if ($scope.Day) {
					query(2, 0);
				} else if ($scope.LastWeek) {
					query(2, 1);
				} else if ($scope.CurrentWeek) {
					query(2, 2);
				} else if ($scope.LastMonth) {
					query(2, 3);
				} else if ($scope.CurrentMonth) {
					query(2, 4);
				} else if ($scope.AllDay) {
					query(2, 5);
				};
			} else {
				$scope.All = true;
				$scope.$digest();
			}
		};

		//当天
		$scope.cbCurrentDay = function() {
			if ($scope.Day) {
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 0);
				} else if ($scope.ConnectArea) {
					query(1, 0);
				} else if ($scope.All) {
					query(2, 0);
				};
			} else {
				$scope.Day = true;
				$scope.$digest();
			}
		};

		//上周
		$scope.cbLastWeek = function() {
			if ($scope.LastWeek) {
				$scope.Day = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 1);
				} else if ($scope.ConnectArea) {
					query(1, 1);
				} else if ($scope.All) {
					query(2, 1);
				};
			} else {
				$scope.LastWeek = true;
				$scope.$digest();
			}
		};

		//本周
		$scope.cbCurrentWeek = function() {
			if ($scope.CurrentWeek) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 2);
				} else if ($scope.ConnectArea) {
					query(1, 2);
				} else if ($scope.All) {
					query(2, 2);
				};
			} else {
				$scope.CurrentWeek = true;
				$scope.$digest();
			}
		};

		//上月
		$scope.cbLastMonth = function() {
			if ($scope.LastMonth) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.CurrentMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 3);
				} else if ($scope.ConnectArea) {
					query(1, 3);
				} else if ($scope.All) {
					query(2, 3);
				};
			} else {
				$scope.LastMonth = true;
				$scope.$digest();
			}
		};

		//本月
		$scope.cbCurrentMonth = function() {
			if ($scope.CurrentMonth) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.AllDay = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 4);
				} else if ($scope.ConnectArea) {
					query(1, 4);
				} else if ($scope.All) {
					query(2, 4);
				};
			} else {
				$scope.CurrentMonth = true;
				$scope.$digest();
			}
		};

		//全部时间
		$scope.cbAllDate = function() {
			if ($scope.AllDay) {
				$scope.Day = false;
				$scope.LastWeek = false;
				$scope.CurrentWeek = false;
				$scope.LastMonth = false;
				$scope.CurrentMonth = false;
				$scope.$digest();

				if ($scope.ProductComplete) {
					query(0, 5);
				} else if ($scope.ConnectArea) {
					query(1, 5);
				} else if ($scope.All) {
					query(2, 5);
				};
			} else {
				$scope.AllDay = true;
				$scope.$digest();
			}
		};

		//同步ERP
		$scope.btnSyncERPComplete = function() {
			$scope.Module._RcvRecord.Records = [];
			var rcds = new Array();
			for (var i in $scope.Module.RcvRecord.Records) {
				//if ($scope.Module.RcvRecord.Records[i].IsSelected && $scope.Module.RcvRecord.Records[i].RcvBusinessType == 0 && $scope.Module.RcvRecord.Records[i].ERPID == null) {
				//rcds.push($scope.Module.RcvRecord.Records[i]);
				//};
				if ($scope.Module.RcvRecord.Records[i].RcvBusinessType == 0 && ($scope.Module.RcvRecord.Records[i].ERPID == null || $scope.Module.RcvRecord.Records[i].ERPID.length == 0)) {
					rcds = rcds.concat(angular.copy($scope.Module.RcvRecord.Records[i]));
				};

			};
			var sumRcds = new Array();
			for (var i = 0; i < rcds.length; i++) {
				if (sumRcds.length == 0) { //追加
					sumRcds.push(rcds[i]);
				} else {
					for (var j = 0; j < sumRcds.length; j++) {
						if (rcds[i].BusinessDocID._id == sumRcds[j].BusinessDocID._id && rcds[i].RcvUser._id == sumRcds[j].RcvUser._id) { //按照MO和User汇总入库量
							sumRcds[j].RcvQty += rcds[i].RcvQty;
							continue;
						} else { //追加
							if (j == sumRcds.length - 1) {
								sumRcds.push(rcds[i]);
								break;
							};
						}
					};
				}
			};

			$scope.Module._RcvRecord.Records = sumRcds;
			// $scope.Module._RcvRecord.RecordCount = sumRcds.length;
			// $scope.Module._RcvRecord.firstPage();
			$scope.Module._RcvRecord.emitOnLoadEvent();
			// if (rcds.length < 1) {
			// 	BaseFunction.alert("请先勾选记录再执行该操作！", "操作有误");
			// } else {

			// };
		}

		//完工
		$scope.btnExecute = function() {
			// var context = {
			// 	CultureName: "zh-CN",
			// 	EntCode: "1",
			// 	OrgCode: "0001",
			// 	UserCode: "demo"
			// };
			// var completeDTOList = [];

			// for (var i = 0; i < $scope.Module._RcvRecord.Records.length; i++) {
			// 	var rcd = $scope.Module._RcvRecord.Records[i];
			// 	var QXCompleteData = {
			// 		Lot: rcd.BarcodeMaster.ShipLotNumber,
			// 		//Lot: 'fan-12',
			// 		RcvQty: rcd.RcvQty,
			// 		//RcvQty: 1,
			// 		MOID: rcd.BusinessDocID._id,
			// 		RcvUser: rcd.RcvUser._id
			// 	};
			// 	completeDTOList.push(QXCompleteData);
			// };

			// var params = {
			// 	context,
			// 	completeDTOList
			// };

			// $http.post("http://101.251.244.131/U9/RestServices/UFIDA.U9.ISV.QXCompleteSV.QX.ICreateCompleteSV.svc/Do", params).success(function(data) {
			// 	for (var i = 0; i < data.d.length; i++) {
			// 		for (var k = 0; k < $scope.Module._RcvRecord.Records.length; k++) {
			// 			if ($scope.Module._RcvRecord.Records[k].BusinessDocID._id == data.d[i].MOID && $scope.Module._RcvRecord.Records[k].RcvUser._id == data.d[i].RcvUser) {
			// 				if (data.d[i].ComID > 0) { //完工成功，回写完工ID
			// 					$scope.Module._RcvRecord.Records[k].HandleResult = '成功';
			// 				} else { //完工失败
			// 					$scope.Module._RcvRecord.Records[k].HandleResult = '失败';
			// 				}
			// 				$scope.Module._RcvRecord.emitOnLoadEvent();
			// 			}
			// 		};

			// 		for (var j = 0; j < $scope.Module.RcvRecord.Records.length; j++) {
			// 			if ($scope.Module.RcvRecord.Records[j].BusinessDocID._id == data.d[i].MOID && $scope.Module.RcvRecord.Records[j].RcvUser._id == data.d[i].RcvUser && $scope.Module.RcvRecord.Records[j].RcvBusinessType == 0 && ($scope.Module.RcvRecord.Records[j].ERPID == null || $scope.Module.RcvRecord.Records[j].ERPID.length == 0)) {
			// 				if (data.d[i].ComID > 0) { //完工成功，回写完工ID
			// 					$scope.Module.RcvRecord.Records[j].ERPID = data.d[i].ComID;
			// 					//$scope.Module.RcvRecord.save();
			// 					$scope.Module.RcvRecord.updateByValue({
			// 						_id: $scope.Module.RcvRecord.Records[j]._id
			// 					}, {
			// 						ERPID: data.d[i].ComID
			// 					});
			// 					$scope.Module.RcvRecord.emitOnLoadEvent();
			// 				} else { //完工失败

			// 				}
			// 			};
			// 		};

			// 	};
			// }).error(function(err) {
			// 	console.log(err);
			// });
		}

		function query(bussinessType, dateType) {
			//业务类型(成品完工、交接区入库、全部)
			//时间类型(当天、上周、本周、上月、本月、全部)

			var condit = {};

			if (bussinessType == 0) { //成品完工
				condit['RcvBusinessType'] = 0
			} else if (bussinessType == 1) { //交接区入库
				condit['RcvBusinessType'] = 1
			} else if (bussinessType == 2) { //全部

			};

			if (dateType == 0) { //当天
				condit['RcvDateTime'] = {
					'$gte': curday + ' 00:00:00',
					'$lte': curday + ' 23:59:59'
				}
			} else if (dateType == 1) { //上周
				condit['RcvDateTime'] = {
					'$gte': lastweekstart,
					'$lte': lastweekend
				}
			} else if (dateType == 2) { //本周
				condit['RcvDateTime'] = {
					'$gte': curweekstart,
					'$lte': curweekend
				}
			} else if (dateType == 3) { //上月
				condit['RcvDateTime'] = {
					'$gte': lastmonthstart,
					'$lte': lastmonthend
				}
			} else if (dateType == 4) { //本月
				condit['RcvDateTime'] = {
					'$gte': curmonthstart,
					'$lte': curmonthend
				}
			} else if (dateType == 5) { //全部

			};

			$scope.Module.RcvRecord.Condition = condit;

			$scope.Module.RcvRecord.find(condit, null, $scope.Module.RcvRecord.Populate, function(rds) {
				$scope.Module.RcvRecord.Records = rds;
				//$scope.Module.RcvRecord.RecordCount = rds.length;
				//$scope.Module.RcvRecord.firstPage();
				$scope.Module.RcvRecord.emitOnLoadEvent();
			})
		}

		//计算起止时间
		function calCurrentMonthTime(isStartTime, dateType) { //isStartTime-判断起止，0-当天，1-上周，2-本周，3-上月，4-本月，5-全部
			var now = new Date(); //当前日期 
			var nowDayOfWeek = now.getDay(); //今天本周的第几天
			var nowDay = now.getDate(); //当前日
			var nowMonth = now.getMonth(); //当前月 
			var nowYear = now.getYear(); //当前年 
			nowYear += (nowYear < 2000) ? 1900 : 0; //
			var lastMonthDate = new Date(); //上月日期
			lastMonthDate.setDate(1);
			lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
			var lastYear = lastMonthDate.getYear();
			var lastMonth = lastMonthDate.getMonth();

			var rtnTime;
			if (dateType == 0) { //当天
				if (isStartTime) {
					var getCurrentDate = new Date(nowYear, nowMonth, nowDay);
					rtnTime = formatDate(getCurrentDate)
				} else {

				};
			} else if (dateType == 1) { //上周
				if (isStartTime) {
					var getUpWeekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7 + 1);
					rtnTime = formatDate(getUpWeekStartDate);
				} else {
					var getUpWeekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek - 7 + 1));
					rtnTime = formatDate(getUpWeekEndDate);
				};
			} else if (dateType == 2) { //本周
				if (isStartTime) {
					var getWeekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
					rtnTime = formatDate(getWeekStartDate);
				} else {
					var getWeekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1));
					rtnTime = formatDate(getWeekEndDate);
				};
			} else if (dateType == 3) { //上月
				if (isStartTime) {
					var getLastMonthStartDate = new Date(nowYear, lastMonth, 1);
					rtnTime = formatDate(getLastMonthStartDate);
				} else {
					var getLastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(nowYear, lastMonth));
					rtnTime = formatDate(getLastMonthEndDate);
				};
			} else if (dateType == 4) { //本月
				if (isStartTime) {
					var getMonthStartDate = new Date(nowYear, nowMonth, 1);
					rtnTime = formatDate(getMonthStartDate);
				} else {
					var getMonthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowYear, nowMonth));
					rtnTime = formatDate(getMonthEndDate);
				};
			} else if (dateType == 5) { //全部
				if (isStartTime) {

				} else {

				};
			};

			return rtnTime;
		}

		function getMonDayAndSunDay() {
			//datevalue = new Date();
			var now = new Date(); //当前日期 
			var nowYear = now.getYear();
			nowYear += (nowYear < 2000) ? 1900 : 0; //
			var nowMonth = now.getMonth() + 1;
			var dateValue = nowYear + "-" + nowMonth + "-" + now.getDate();
			var arr = dateValue.split("-");
			//月份-1 因为月份从0开始 构造一个Date对象  
			var date = new Date(arr[0], arr[1] - 1, arr[2]);

			var dateOfWeek = date.getDay(); //返回当前日期的在当前周的某一天（0～6--周日到周一）  

			var dateOfWeekInt = parseInt(dateOfWeek, 10); //转换为整型  

			if (dateOfWeekInt == 0) { //如果是周日  
				dateOfWeekInt = 7;
			}
			var aa = 7 - dateOfWeekInt; //当前于周末相差的天数  

			var temp2 = parseInt(arr[2], 10); //按10进制转换，以免遇到08和09的时候转换成0  
			var sunDay = temp2 + aa; //当前日期的周日的日期  
			var monDay = sunDay - 6 //当前日期的周一的日期  

			var startDate = new Date(arr[0], arr[1] - 1, monDay);
			var endDate = new Date(arr[0], arr[1] - 1, sunDay);

			var sm = parseInt(startDate.getMonth()) + 1; //月份+1 因为月份从0开始  
			var em = parseInt(endDate.getMonth()) + 1;

			//  alert("星期一的日期："+startDate.getYear()+"-"+sm+"-"+startDate.getDate());  
			//  alert("星期日的日期："+endDate.getYear()+"-"+em+"-"+endDate.getDate());  
			var start = nowYear + "-" + sm + "-" + startDate.getDate();
			var end = nowYear + "-" + em + "-" + endDate.getDate();
			var result = new Array();
			result.push(start);
			result.push(end);

			return result;
		}

		function getLastMonDayAndSunDay(week) {
			var w = week.split("-");
			var getUpWeekStartDate;
			var day = parseInt(w[2]);
			if (day > 7) {
				getUpWeekStartDate = new Date(w[0], w[1], w[2] - 7);
			} else {
				getUpWeekStartDate = new Date(w[0], w[1], w[2] - 6);
			}

			return formatWeekDate(getUpWeekStartDate);
		};

		//获得某月的天数
		function getMonthDays(nowYear, myMonth) {
			var monthStartDate = new Date(nowYear, myMonth, 1);
			var monthEndDate = new Date(nowYear, myMonth + 1, 1);
			var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
			return days;
		}

		//格式化时间
		function formatDate(date) {
			var myyear = date.getFullYear();
			var mymonth = date.getMonth() + 1;
			var myweekday = date.getDate();
			return (myyear + "-" + mymonth + "-" + myweekday);
		}

		//格式化时间
		function formatWeekDate(date) {
			var myyear = date.getFullYear();
			var mymonth = date.getMonth();
			var myweekday = date.getDate();
			return (myyear + "-" + mymonth + "-" + myweekday);
		}
	}
]);